package cn.gailvlun.gll.presentation.chat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileNotFoundException;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.ActivityPhotoBinding;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.StringUtil;
import cn.gailvlun.gll.util.ToastUtil;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;


public class PhotoActivity extends BaseActivity {

    public static void openActivity(Context context, String url, @Nullable Bundle transBundle) {
        Intent intent = new Intent(context, PhotoActivity.class);
        intent.putExtra("photoUrl", url);
        context.startActivity(intent, transBundle);
    }

    private ActivityPhotoBinding mBinding;

    @Override
    protected void initComponent() {
        supportPostponeEnterTransition();

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_photo);
        mBinding.setPresenter(new Presenter());
    }

    @Override
    protected void createHandler() {
    }

    private String photoUrl;
    private String fileName;
    private Bitmap mBitmap;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        photoUrl = getIntent().getStringExtra("photoUrl");
        fileName = StringUtil.getFileNameByUrl(photoUrl);

        Glide.with(mContext)
                .asBitmap()
                .load(photoUrl)
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        supportStartPostponedEnterTransition();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        supportStartPostponedEnterTransition();
                        return false;
                    }
                })
                .into(new ImageViewTarget<Bitmap>(mBinding.photoView) {
                    @Override
                    protected void setResource(@Nullable Bitmap resource) {
                        if (resource != null) {
                            mBitmap = resource;
                            mBinding.photoView.setImageBitmap(resource);
                        }
                    }
                });
    }

    public class Presenter {
        public void onClick() {
            onBackPressed();
        }

        public boolean onSave() {
            final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(mContext, R.style.CustomBottomSheetDialogTheme);
            bottomSheetDialog.setContentView(R.layout.dialog_photo_save);
            View save = bottomSheetDialog.findViewById(R.id.save);
            View cancel = bottomSheetDialog.findViewById(R.id.cancel);
            save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new RxPermissions(mContext)
                            .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        saveFile();
                                    } else {
                                        ToastUtil.showShort("没有权限");
                                    }
                                }
                            });
                }
            });
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    bottomSheetDialog.dismiss();
                }
            });
            bottomSheetDialog.show();
            return true;
        }
    }

    private void saveFile() {
        final File path = new File(Environment.getExternalStorageDirectory(), "gailvlun/images/");
        if (FileUtils.createOrExistsDir(path)) {
            File theSaveFile = new File(path, fileName);
            Single.just(theSaveFile)
                    .map(new Function<File, File>() {
                        @Override
                        public File apply(File file) throws Exception {
                            ImageUtils.save(mBitmap, file, Bitmap.CompressFormat.PNG);
                            saveToMedia(file);
                            return file;
                        }
                    })
                    .compose(RxUtil.<File>applySingleScheduler())
                    .subscribe(new SingleObserver<File>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onSuccess(File file) {
                            FileUtils.deleteFile(file);
                            ToastUtil.showShort("保存成功");
                        }

                        @Override
                        public void onError(Throwable e) {
                            ToastUtil.showShort("保存失败");
                        }
                    });
        }
    }

    private void saveToMedia(File file) {
        
        try {
            MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
        mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));
    }
}
